package com.xzx.mybatis;

import com.xzx.mybatis.mapper.DeptMapper;
import com.xzx.mybatis.mapper.EmployeeMapper;
import com.xzx.mybatis.po.DeptPO;
import com.xzx.mybatis.po.EmployeePO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/6/21 12:40
 */
@Slf4j
public class Main {

    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void getSqlSessionFactory() throws IOException {
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
    }

     @Test
    public void test() {
        // true表示自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        EmployeePO po = mapper.getById(3L);
        System.out.println(po);
        sqlSession.close();
    }


    @Test
    public void testCacheLevel1() {
        // true表示自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        EmployeePO po = mapper.getById(3L);
        System.out.println(po);
        EmployeePO po1 = mapper.getByName("发财");
        System.out.println(po1);
        System.out.println(po == po1);
        sqlSession.close();
    }

    @Test
    public void testCacheLevel2() {
        // true表示自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        EmployeePO po = mapper.getById(3L);
        System.out.println(po);
        DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
        DeptPO deptPO = deptMapper.getById(1);
        System.out.println(deptPO);
        sqlSession.close();

        SqlSession sqlSession1 = sqlSessionFactory.openSession(true);
        EmployeeMapper mapper1 = sqlSession1.getMapper(EmployeeMapper.class);
        EmployeePO employeePO = new EmployeePO();
        employeePO.setLastName("发财3");
        mapper1.insert(employeePO);
        EmployeePO po1 = mapper1.getById(3L);
        System.out.println(po1);
        System.out.println(po == po1);// 这里是false，因为底层默认是拷贝了一个对象，而不是直接返回引用
        DeptMapper deptMapper1 = sqlSession1.getMapper(DeptMapper.class);
        DeptPO deptPO1 = deptMapper1.getById(1);
        System.out.println(deptPO1);
        sqlSession1.close();

    }
}